package com.danke.lib.banner.widget.loopviewpager;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

/**
 * @author wpq
 * @version 1.0
 */
public class BannerViewPager extends ViewPager {

    private static final String TAG = BannerViewPager.class.getSimpleName();

    /**
     * 高/宽
     */
    private float mScale;

    public BannerViewPager(@NonNull Context context) {
        super(context);
    }

    public BannerViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (scaleValid()) {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int childShouldWidth = width - getPaddingStart() - getPaddingEnd();
            int childShouldHeight = (int) (childShouldWidth * mScale);
//            int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childShouldWidth, MeasureSpec.EXACTLY);
//            int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childShouldHeight, MeasureSpec.EXACTLY);
//            for (int i = 0; i < getChildCount(); i++) {
//                View child = getChildAt(i);
//                if (child != null) {
//                    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
//                }
//            }
            int shouldHeight = childShouldHeight + getPaddingTop() + getPaddingBottom();
//            Log.e("onMeasure", "width=" + width + ", shouldHeight=" + shouldHeight + ", childShouldWidth=" + childShouldWidth + ", childShouldHeight=" + childShouldHeight);
//            setMeasuredDimension(width, shouldHeight);
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(shouldHeight, MeasureSpec.EXACTLY));
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    public float getScale() {
        return mScale;
    }

    public void setScale(float scale) {
        mScale = scale;
    }

    private boolean scaleValid() {
        return mScale > 0 && mScale <= 1;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        // https://github.com/chrisbanes/PhotoView#issues-with-viewgroups
        try {
            return super.onInterceptTouchEvent(ev);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // https://blog.csdn.net/sinat_15411661/article/details/51504965
        try {
            return super.onTouchEvent(ev);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
